package org.zjt.java.demo.config.security;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.zjt.java.demo.entity.User;
import org.zjt.java.demo.entity.UserQuery;
import org.zjt.java.demo.repository.UserRepository;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class UserDetailsServiceImple implements UserDetailsService {

	private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailsServiceImple.class);

	@Autowired
	private UserRepository userRepository;


	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		final Collection<SimpleGrantedAuthority> authorities = new ArrayList();

		UserQuery userQuery = new UserQuery();
		userQuery.createCriteria().andUserNumberEqualTo(username);
		List<User> users = userRepository.selectByExample(userQuery);
		if (CollectionUtils.isEmpty(users))
			return null;
		if (users.size() > 1){
			LOGGER.info("username is not unique :{}", JSONObject.toJSONString(users));
			return null;
		}

		User user = users.get(0);
		authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
		org.springframework.security.core.userdetails.User user1 = new org.springframework.security.core.userdetails.User(username,user.getUserPasswd(),authorities);

		//new org.springframework.security.core.userdetails.User(用户名，加密后的密码)
		return user1;
	}

}